<?php
declare(strict_types=1);

// ids过滤转换
function ids_filter(string $ids, bool $to_array = false, bool $gt_0 = true)
{
    $ids = array_filter(explode(',', $ids), 'is_numeric');
    $ids = array_unique($ids);
    if ($gt_0) {
        $ids = array_filter($ids, fn(int $n)=>$n>0);
    }
    ksort($ids);
    return $to_array ? $ids : implode(',', $ids);
}

// 表名验证
function is_table(string $table): bool
{
    $prefix = pdo()->getConfig('table_prefix');
    return (bool)preg_match('/^' . $prefix . '\w{1,12}$/', $table);
}

// 导航高亮显示
function nav_active(string $nav, string $class = ' class="active"'): string
{
    return ($nav == get_controller()) ? $class : '';
}

// 格式时间
function get_time_ago(int $time): string
{
    $etime = time() - $time;
    if ($etime < 1) {
        return '刚刚';
    }
    $interval = [31536000 => '年前', 2592000 => '个月前', 604800=>'星期前', 86400=>'天前', 3600=>'小时前', 60=>'分钟前', 1=>'秒前'];
    foreach ($interval as $k => $v) {
        $ok = floor($etime / $k);
        if ($ok != 0) {
            return $ok.$v;
        }
    }
    return '刚刚';
}

// 生成form:select
function build_select(string $name, $options, $selected = ''): string
{
    $options = is_array($options)? $options : explode(',', $options);
    $html = "<select name=\"{$name}\" class=\"form-control\" style=\"width:auto;\">\n";
    foreach ($options as $val => $key) {
        if ($selected == $val) {
            $html .= "\t<option value=\"{$val}\" selected=\"selected\">{$key}</option>\n";
        } else {
            $html .= "\t<option value=\"{$val}\">{$key}</option>\n";
        }
    }
    $html .= "</select>\n";
    return $html;
}

// 生成form:radios
function build_radios(string $name, $options, $selected = ''): string
{
    $options = is_array($options)? $options : explode(',', $options);
    $html = '';
    foreach ($options as $val => $key) {
        if ($selected == $val) {
            $html .= "<label><input type=\"radio\" name=\"{$name}\" value=\"{$val}\" checked=\"checked\" />{$key}</label>\n";
        } else {
            $html .= "<label><input type=\"radio\" name=\"{$name}\" value=\"{$val}\" />{$key}</label>\n";
        }
    }
    return $html;
}

// 获取文档起启页ID
function get_start_id(int $doc_id): int
{
    $doc = widget('doc_dir')->get($doc_id);
    if (!empty($doc)) {
        return array_key_first($doc);
    }
    return 0;
}

//获取缩略图
function aphp_thumb(string $url, int $i):string
{
    if ($i>40) {
        $i = $i % 40;
    }
    return !empty($url)? $url : __STATIC__.'/img/thumb/'.$i.'.jpg';
}
